package configruation

import (
	"gitee.com/shijun123456/kcgin"
	"sinery.net.goft/src/common"
	"sinery.net.goft/src/dao"
	"strconv"
	"time"
	"xorm.io/xorm"
	"xorm.io/xorm/log"
	"xorm.io/xorm/names"
)

func (this *DBConfig) Xorm() *dao.XormAdapter {
	engine, err := xorm.NewEngine(kcgin.AppConfig.String("db.type"), common.GetMysqlDSN())
	if err != nil {
		panic(err.Error())
	}
	maxid, _ := strconv.Atoi(kcgin.AppConfig.String("db.maxidle"))
	maxConn, _ := strconv.Atoi(kcgin.AppConfig.String("db.maxconn"))
	//最大的链接数
	maxLifeTime, _ := strconv.Atoi(kcgin.AppConfig.String("db.maxlifetime"))
	maxLife := time.Duration(int64(maxLifeTime))
	engine.DB().SetMaxIdleConns(maxid)
	engine.DB().SetMaxOpenConns(maxConn)
	engine.DB().SetConnMaxLifetime(maxLife)

	logger, err := common.Logger()
	if err != nil {
		panic(err.Error())
	}
	tbMapper := names.NewPrefixMapper(names.SnakeMapper{}, "kc_")
	engine.SetTableMapper(tbMapper)
	if kcgin.KcConfig.RunMode != "prod" {
		engine.ShowSQL(true)
		engine.SetLogLevel(log.LOG_DEBUG)
		engine.SetLogger(log.NewSimpleLogger(logger))
	}

	return &dao.XormAdapter{
		Engine: engine,
	}
}
